<template>
  <div class="main">
    <div class="search_div">
      <!--      <input class="search_div_input">-->
      <!--      <button class="search_div_button" @click="toSearch">搜索</button>-->
      <div class="line-zero-search">
        <el-autocomplete
          placeholder="请输入内容"
          v-model="queryData.searchWord"
          class="input-with-select"
          popper-class="el-fin-add"
          :fetch-suggestions="querySearchAsync"
          @select="handleSelect">
          <el-select v-model="queryData.db" slot="prepend" placeholder="资源库">
            <el-option label="全部" value=""></el-option>
            <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in dbList"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-autocomplete>
      </div>
    </div>
    <div class="search_result">
      <div class="facet">
        <div class="facet_item" v-for="(item, index) in facetData">
          <div class="facet_item_name">
            <span>{{item.nameZh}}</span>
            <span @click="openCloseFacetItem(item)">
              <i :class="[facetOpen[item.nameEn]?'el-icon-plus':'el-icon-minus']"></i>
            </span>
          </div>
          <div class="facet_item_value"
               v-show="!facetOpen[item.nameEn]">
            <el-tree
              :data="item.array"
              :props="props"
              :load="loadNode"
              :ref="item.nameEn+'Tree'"
              :default-checked-keys="facetCheckMap[item.nameEn]"
              node-key="nameVal"
              lazy
              show-checkbox
              @check="handleCheckClick">
                <span class="facet_item_value_node" slot-scope="{ node, data }">
                    <el-tooltip class="item" effect="dark" :content="node.label" placement="right">
                       <span>{{ getTreeLabel(node.label, 10) }}</span>
                    </el-tooltip>
                    <span>
                      <a class="facet_item_value_count">{{data.count || 0}}</a>
                    </span>
                </span>
            </el-tree>
            <span class="facet_item_more" v-show="!facetNotMore[item.nameEn]" @click="loadMore(item, index)">更多...</span>
          </div>
        </div>
      </div>
      <div class="list">
        <div style="margin-top: 10px;">
          <el-link :underline="false">共找到{{listData.count}}条结果</el-link>
          <el-link type="primary" style="margin-left: 20px" @click="weightRules.open=true">设置权重</el-link>
          <el-select v-model="queryData.pageSizes" @change="pageSelectChange" placeholder="设置每页展示条数" size="mini"
                     class="page_select">
            <el-option
              v-for="item in pageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-link :underline="false"  style="margin-left: 20px" >检索耗时:{{listData.time}}秒</el-link>
        </div>
        <div class="list_item" v-for="(item, index) of listData.list">
          <div style="margin: 15px 0;font-size: 16px;font-weight: 700;color: #215da9;cursor: pointer;"
               v-html="((queryData.pageNumber-1)*queryData.pageSizes)+index+1+'.'+item.title" @click="handleLookDetail(item)"></div>
          <div style="margin: 10px 0 10px 20px;">
            <span style="color: #666;">[{{item.classZh}}]</span>
            <div style="display: inline">
              <span style="margin: 0 6px;text-decoration: none;color: #417dc9;cursor: pointer;"
                    v-for="authorItem of item.author" v-html="authorItem"></span>
            </div>
          </div>
          <div style="margin: 10px 0 10px 20px; " v-html="item.description">
          </div>
          <div style="margin: 10px 0 10px 20px;" v-if="item.keyword">
            <span
              style="display: inline-block;margin-right: 10px;text-decoration: underline;cursor: pointer;color: #666;"
              v-for="keywordItem of item.keyword" v-html="keywordItem" @click="handleClickKeywords(keywordItem)"></span>
          </div>
        </div>
        <div style="display: flex;justify-content: center;" v-show="listData.count > queryData.pageNumber">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="queryData.pageNumber"
            :page-size="queryData.pageSizes"
            layout="prev,pager,next"
            :total="listData.count>1000?1000:listData.count">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog :title="weightRules.title" :visible.sync="weightRules.open" width="30%" :close-on-click-modal="false"
               append-to-body>
      <div v-for="item of weightRules.fieldWeight" style="margin-top: 10px;display: flex">
        <span style="display: flex;align-items: center;width: 10%">{{item.nameZh}}:</span>
        <el-slider
          style="width: 80%;margin-left: 20px"
          v-model="item.weight"
          :step="5">
        </el-slider>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleWeightSearch">确 定</el-button>
        <el-button @click="weightRules.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="detailsDialog.title" :visible.sync="detailsDialog.open" width="60%" :close-on-click-modal="false"
               append-to-body>
<!--      <el-descriptions :title="detailsDialog.resourceTitle" :column="1" >-->
<!--        <el-descriptions-item :label="k" v-for="(v,k) in detailsDialog.fields"><span v-for="it of multiValueDisplay(v)" style="margin: 0 10px 0 0" v-html="it"></span></el-descriptions-item>-->
<!--      </el-descriptions>-->
      <label v-html="detailsDialog.resourceTitle" style="font-size: 25px;"></label>
      <el-divider></el-divider>
      <div v-for="item in detailsDialog.fields" style="margin: 10px 0;font-size: 18px;">
        <label style="margin-right: 10px">{{item.nameZh}}:</label>

        <span v-if="item.dataTypeName=='filePath'">
          <el-link v-for="it of multiValueDisplay(item.value)" :href="`${baseUrl}${it}`" :underline="false" target="_blank"  style="margin-right: 10px;">
            <span class="el-icon-document" style="font-size: 18px;"> {{ getFileName(it) }}</span>
          </el-link>
        </span>
        <span v-else>
          <span v-for="it of multiValueDisplay(item.value)" v-html="it" style="margin-right: 10px" ></span>
        </span>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="detailsDialog.open=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import * as SEARCH from "@/api/web/search";
    import AESENCRY from "@/utils/crypto"

    export default {
        name: "list",
        data() {
            return {
                baseUrl: process.env.VUE_APP_BASE_API,
                pageOptions: [{
                    value: 10,
                    label: '每页展示10条'
                }, {
                    value: 20,
                    label: '每页展示20条'
                }, {
                    value: 30,
                    label: '每页展示30条'
                }, {
                    value: 40,
                    label: '每页展示40条'
                }, {
                    value: 50,
                    label: '每页展示50条'
                }],
                weightRules: {
                    open: false,
                    title: "设置权重",
                    fieldWeight: []
                },
                detailsDialog: {
                    open: false,
                    title: "资源详情",
                    resourceTitle: "111",
                    fields: []
                },
                facetData: [],
                facetCheckMap: {},
                //每项最大分面树
                facetMaxCount: 20,
                //每项分面默认加载数
                facetDefaultCount: 5,
                //分面是否展开 true:当前分面处于关闭。 false:当前分面处于展开
                facetOpen: {},
                //分面是否可以加载更多。true:不可加载。false:可继续加载
                facetNotMore: {},
                loading: {
                    lock: true,
                    text: "拼命加载中",
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                },
                listData: {
                    list: [],
                    count: 0,
                    time: 0
                },
                restaurants: [],
                queryData: {
                    searchWord: "",
                    db: "",
                    pageNumber: 1,
                    pageSizes: 10,
                },
                props: {
                    label: 'name',
                    children: 'zones',
                    isLeaf: 'isSon'
                },
            }
        },
        props: {
            dbList: {
                type: Array,
                default: () => {
                    return null
                }
            }
        },
        mounted() {
            let data = this.$route.params;
            let db = data.db || "";
            let searchWord = data.searchWord || "";
            this.$set(this.queryData, "db", db);
            this.$set(this.queryData, "searchWord", searchWord);
            //加载本地检索记录
            this.restaurants = this.loadLocalRecordAll();
            const loading = this.$loading(this.loading);
            Promise.all([this.searchData(),this.searchFacet()]).then(() => {
                loading.close();
            }).catch(err => {
                console.error(err)
            });
        },
        computed: {
            getTreeLabel() {
                return (lable, num) =>{
                  if(lable.length > num){
                      return lable.substring(0,num)+"...";
                  }
                  return lable;
                }
            },
            multiValueDisplay() {
                return (val) => {
                    if(typeof val === "string"){
                        return [val];
                    }
                    return val;
                }
            },
            // 获取文件名称
            getFileName() {
                return (name) => {
                    if (name.lastIndexOf("/") > -1) {
                        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
                    } else {
                        return "";
                    }
                }
            },
        },
        methods: {
            pageSelectChange() {
                const loading = this.$loading(this.loading);
                Promise.all([this.searchData()]).then(() => {
                    loading.close();
                }).catch(err => {
                });
            },
            handleCurrentChange(page) {
                const loading = this.$loading(this.loading);
                this.$set(this.queryData, "pageNumber", page);
                Promise.all([this.searchData()]).then(() => {
                    loading.close();
                }).catch(err => {
                });
            },
            openCloseFacetItem(item) {
                let facetName = item.name;
                this.$set(this.facetOpen, facetName, !this.facetOpen[facetName])
            },
            loadLocalRecordAll() {
                let querystore = JSON.parse(this.$cache.local.get("QUERYSTORE") || "[]");
                let queryList = [];
                queryList = querystore.map(item => {
                    return {
                        value: decodeURIComponent(item.q),
                    }
                });
                return queryList
            },
            handleClickKeywords(obj) {
                let db = this.queryData.db;
                let pageSizes = this.queryData.pageSizes;
                if(!obj.startsWith("<span style='color:red'>") && !obj.endsWith("</span>")){
                    this.queryData = {};
                    this.$set(this.queryData, "searchWord", obj);
                    this.$set(this.queryData, "db", db);
                    this.$set(this.queryData, "pageNumber", 1);
                    this.$set(this.queryData, "pageSizes", pageSizes);
                    this.handleSearch();
                }
            },
            handleSelect(obj) {
                let db = this.queryData.db;
                let pageSizes = this.queryData.pageSizes;
                this.queryData = {};
                this.$set(this.queryData, "searchWord", obj.value);
                this.$set(this.queryData, "db", db);
                this.$set(this.queryData, "pageNumber", 1);
                this.$set(this.queryData, "pageSizes", pageSizes);
                this.handleSearch();
            },
            handleWeightSearch() {
                const loading = this.$loading(this.loading);
                this.weightRules.open = false;
                let weightField = {};
                this.weightRules.fieldWeight.map(item => {
                    if (item.weight) {
                        weightField[item.nameEn] = item.weight;
                    }
                });
                this.$set(this.queryData, "pageNumber", 1);
                this.$set(this.queryData, "weightRules", weightField);
                Promise.all([this.searchData()]).then(() => {
                    loading.close();
                }).catch(err => {
                });
            },
            handleSearch() {
                this.$emit('addLocalSearchRecord', this.queryData);

                this.facetCheckMap = {};
                //点击查询
                const loading = this.$loading(this.loading);
                this.$set(this.queryData, "pageNumber", 1);
                Promise.all([this.searchData(),this.searchFacet()]).then(() => {
                    loading.close();
                }).catch(err => {
                });
            },
            querySearchAsync(queryString, cb) {
                cb([]);
                // if (this.queryData.searchWord) {
                //     const data = {
                //         searchWord: this.queryData.searchWord,
                //         pageNumber: 1,
                //         pageSizes: 6
                //     };
                //     SEARCH.searchCompletion(data).then(response => {
                //         let list = response.data.list.map(item => {
                //             return {
                //                 value: item.title
                //             }
                //         });
                //         cb(list);
                //     });
                // } else {
                //     let restaurants = this.restaurants;
                //     cb(restaurants);
                // }
            },
            handleCheckClick(data, checked, indeterminate) {
                const loading = this.$loading(this.loading);
                let field = data.field;
                var mapValue = this.$refs[(field + "Tree")][0].getCheckedKeys();
                this.$set(this.facetCheckMap, field, mapValue);
                this.$set(this.queryData, "appointFacetFieldMap", this.facetCheckMap);
                Promise.all([this.searchData(),this.searchFacet()]).then(() => {
                    loading.close();
                }).catch(err => {
                });
            },
            async searchData() {
                //查询列表
                await SEARCH.searchList(this.queryData).then(response => {
                    this.listData.list = response.data.list;
                    this.listData.count = response.data.count;
                    this.listData.time = response.data.time;
                    let fieldWeight = response.data.searchField.map(item => {
                        let fieldWeight = this.weightRules.fieldWeight;
                        let filterWeight = [];
                        if (fieldWeight.length) {
                            filterWeight = fieldWeight.filter(x => x.nameEn === item.nameEn);
                        }
                        let weightVal = 0;
                        if (filterWeight.length) {
                            weightVal = filterWeight[0].weight || 0;
                        }
                        return {
                            nameEn: item.nameEn,
                            nameZh: item.nameZh,
                            weight: weightVal
                        }
                    });
                    this.$set(this.weightRules, "fieldWeight", fieldWeight);
                });
            },
            async searchFacet(data, index, appoint) {
                //如果appoint为空为初始加载
                if (!appoint) {
                    data = {};
                    Object.keys(this.queryData).map(item => {
                        data[item] = this.queryData[item] || ''
                    });
                    data.pageSizes = this.facetDefaultCount;
                }
                //查询分面
                await SEARCH.searchFacet(data).then(response => {
                    let facetFieldList = response.data.facetFieldList;
                    let dictFacetMap = response.data.dictFacetMap;
                    let facetResultMap = response.data.facetResultMap;
                    let facetDataTemp = facetFieldList.map(item => {
                        let array = new Array();
                        let facetResultMapElement = facetResultMap[item.nameEn];
                        // let facetResultMapCount = facetResultMap[item.nameEn].count;
                        let facetResultMapCount = {};
                        let facetResultMapElementLen = Object.keys(facetResultMapElement).length;
                        facetResultMapCount["facetCount"] = facetResultMapElementLen
                        if (facetResultMapCount.facetCount >= this.facetMaxCount || facetResultMapElementLen < data.pageSizes) {
                            this.$set(this.facetNotMore, item.nameEn, true);
                        } else {
                            this.$set(this.facetNotMore, item.nameEn, false);
                        }
                        Object.keys(facetResultMapElement).map(itemEleKey => {
                            // 查询以nameVal 为主
                            let dataEle = {
                                field: item.nameEn,
                                name: itemEleKey,
                                nameVal: itemEleKey,
                                count: facetResultMapElement[itemEleKey],
                                isSon: true
                            };
                            if (item.dictId && item.dictId != "null" && item.dictId != "0") {
                                dataEle["isSon"] = !item.haveChildren;
                                dataEle["nameVal"] = dictFacetMap[item.nameEn + "." + itemEleKey];
                            }
                            if( item.name === "type"){
                                dataEle["nameVal"] = dictFacetMap[item.nameEn + "." + itemEleKey];
                            }
                            array.push(dataEle);
                        });
                        return {
                            ...facetResultMapCount,
                            ...item,
                            array
                        }
                    });
                    if (appoint) {
                        this.facetData.splice(index, 1, ...facetDataTemp);
                    } else {
                        this.facetData = facetDataTemp;
                    }
                });
            },
            //点击加载更多
            loadMore(item, index) {
                const loading = this.$loading(this.loading);
                let facetCount = Number(item.facetCount) + this.facetDefaultCount;
                const data = {
                    searchWord: this.queryData.searchWord,
                    db: this.queryData.db,
                    pageSizes: facetCount,
                    appointFacetField: [item.nameEn],
                    appointFacetFieldMap: this.queryData.appointFacetFieldMap
                };
                Promise.all([this.searchFacet(data, index, true)]).then(() => {
                    loading.close();
                }).catch(err => {
                });

            },
            loadNode(node, resolve) {
                if (node.level === 0) {
                    // return resolve([{ name: 'region',  count: 45 }]);
                    return resolve(node.data);
                }
                if (node.level > 1) return resolve([]);
                setTimeout(() => {
                    const data = [{
                        name: 'leaf',
                        leaf: false,
                        count: 15
                    }, {
                        name: 'zone',
                        leaf: true,
                        count: 30
                    }];

                    resolve(data);
                }, 100);
            },
            handleLookDetail(fieldDetail) {
                const data = {
                    classesEn: fieldDetail.classEn
                };
                SEARCH.detailFields(data).then(response => {
                    let list = response.data.list;
                    this.detailsDialog.open = true;
                    let detailsZh = [];
                    detailsZh.push({
                        nameZh: '资源ID',
                        dataTypeName: "string",
                        value: fieldDetail['id']
                    });
                    detailsZh.push({
                        nameZh: '资源类型',
                        dataTypeName: "string",
                        value: fieldDetail['classZh']+"["+fieldDetail['classEn']+"]"
                    });
                    this.$set(this.detailsDialog, "resourceTitle", fieldDetail.title);
                    list.map(item=>{
                        let fieldDetailElement = fieldDetail[item.nameEn];
                        if(fieldDetailElement){
                            detailsZh.push({
                                nameZh: item.nameZh,
                                nameEn: item.nameEn,
                                dataTypeName: item.dataTypeName,
                                value: fieldDetailElement
                            })
                        }
                    });
                    detailsZh.push({
                        nameZh: '创建时间',
                        dataTypeName: "string",
                        value: fieldDetail['create_time']
                    });
                    detailsZh.push({
                        nameZh: '更新时间',
                        dataTypeName: "string",
                        value: fieldDetail['update_time']
                    });
                    this.$set(this.detailsDialog, "fields", detailsZh);
                });
            }
        }
    }
</script>
<style>
  .el-select .el-input {
    width: 100px;
  }

  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .input-with-select {
    width: 100%;
  }

  .el-find-add {
    width: 100%;
  }

  .input-with-select .el-input__inner {
    height: 50px !important;
    font-size: 18px;
  }

  .el-pager li {
    font-size: 15px;
    font-width: 700;
  }

  .page_select {
    margin-left: 20px;
  }

  .page_select .el-input {
    width: 120px !important;
  }
</style>
<style scoped>
  .main {
    /*height: 1250px;*/
  }

  .search_result {
    display: flex;
    margin: 10px 15%;
  }

  .facet {
    width: 20%;
    margin-right: 20px;
    border: 1px solid #ccc;
  }

  .facet_item {
    /*margin-right: 5%;*/
    /*border: red 1px solid;*/
  }

  .facet_item_name {
    line-height: 40px;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    background-color: #e6e6e6;
    font-size: 14px;
    cursor: pointer;
  }

  .facet_item_name i {
    float: right;
    width: 14px;
    height: 14px;
    margin: 13px 0;
  }

  .facet_item_more {
    font-size: 12px;
    line-height: 35px;
    padding: 0 10px;
    color: #417dc9;
    cursor: pointer;
  }

  .facet_item_value {
    padding: 5px 0;
  }

  .facet_item_value_node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .facet_item_value_count {
    color: #fff;
    background: #99a9bf;
    padding: 3px 8px;
    font-size: 12px;
    line-height: 12px;
    border-radius: 20px;
    text-align: center;
  }


  .list {
    width: 80%;
    border: #1ab394 1px solid;
    padding: 0 20px;
  }

  .query_within_results {
  }

  .query_within_results input {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    height: 28px;
    vertical-align: middle;
    line-height: 28px;
    -webkit-box-sizing: border-box;
    font-size: 12px;
    width: 158px;
    border: 1px solid #ccc;
    padding: 7px 5px;
    margin: 5px 5px;
    outline: unset;
    -webkit-transition: border-color .3s;
    transition: border-color .3s;
  }

  .list_item {
    margin: 10px 0;
    background-color: #e1f3fb;
    padding: 10px;
  }

  .search_div {
    margin: 50px 25%;
    display: flex;
    flex-direction: column;
    position: relative
  }

  .search_div_input {
    padding: 15px;
    border-radius: 20px;
    font-size: 20px;
    font-weight: 500;
  }

  .search_div_button {
    position: absolute;
    right: 0;
    padding: 15px;
    border-radius: 0 20px 20px 0;
    color: rgb(32, 78, 163);
    font-weight: 700;
    width: 100px;
    font-size: 17px;
    background-color: transparent;
    cursor: pointer;

  }


</style>
